const util = require('../../../utils/util.js');
const utils = require('../../../utils/util.js');
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tableNumber: 0,
    tableName: '',
    payType: 1,
    cartResult: [],
    sumPrice: 0,
    company: '',
    createUid: 0,
    showSend: false,
    selList: '',
    isCheck: false,
    loadingMoreHiddens: true,
    reloading: false,
    diningSN: 0,    //扫码餐桌序列号
    saleUid: 0,
  },

  // 加菜
  addFood: function () {
    wx.reLaunch({
      url: '/pages/classes-new/index',
    })
  },

  //获取餐桌设置
  getDiningTable: function () {
    var that = this;
    var method = app.globalData.diningSid !='' ? '/api/Restaurant/GetDiningTable' : '/api/Restaurant/GetDiningBySN'
    var url = app.globalData.host + method + "?showStaff=1&id=" + app.globalData.diningSid + '&sn='+ that.data.diningSN;
    if(app.globalData.diningSid =='' && that.data.diningSN == 0){
      wx.showToast({title: '请重新扫码',icon:'none'})
    }
    wx.request({
      url: url,
      success: function (res) {
        if (res.data.Code == 0) {
          var item = res.data.Data;
          app.globalData.diningSid = item.Id;
          wx.setStorageSync('cardId', item.StaffId);
          that.setData({
            tableNumber: item.TableNumber,
            tableName: item.Name,
            company: item.Company
          })
          if(that.data.createUid ==0 ){
            that.setData({createUid: item.Uid }); //缺少商家ID时才设置
          }
          that.getStaffExtend(item.StaffId);
          that.getCartInfo();
        }
      },
    })
  },

  //先用餐模式确认订单
  sureSend: function () {
    // 获取核销权限及优惠券弹窗
    let that = this;
    that.setData({
      showSend: false
    })
    if (that.data.createUid == app.globalData.userInfo.Uid || that.data.isCheck) {//商家自己、核销员
      wx.reLaunch({
        url: '../businessVerify/index',
      })
    } else {
      wx.navigateTo({
        url: '../orderPayDine/index?sel=' + this.data.selList + '&sumprice=' + this.data.sumPrice + '&saleUid=' + that.data.saleUid,
      })
    }
  },

  closeSend: function () {
    this.setData({
      showSend: !this.data.showSend
    })
  },

  getCouponCheck: function () {
    let that = this;
    let cardid = wx.getStorageSync('cardId');    
    wx.request({
      url: app.globalData.host + '/api/staff/GetCouponCheck?staffId=' + cardid + '&uid=' + app.globalData.userInfo.Uid,
      success: function (res) {
        if (res.data.Code == 0) {
          if (res.data.Data.length > 0) {         
            that.setData({isCheck: true})
          }
          setTimeout(function () {
            if (app.globalData.userInfo.Uid == that.data.createUid || that.data.isCheck) {  
              //管理员,订单确认订单
              utils.confirm('是否进入店员操作？',function(){
                wx.reLaunch({url: '../businessVerify/index'})
              })
            }
          }, 500);          
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    let createUid = options.seltoid ? options.seltoid : this.data.createUid;
    let saleUid = options.saleUid ? options.saleUid : this.data.saleUid;
    this.setData({
      createUid: createUid, //商家ID
      saleUid: saleUid      //销售员,带货员
    })
    // let params = decodeURIComponent(options.scene);
    // if (options.q) {
    //   let url = decodeURIComponent(options.q); //扫普通二维码      
    //   params = utils.getQuery(url,'scene');
    //   params = params =='' ? url : params;
    // }

    // if (params && params != 'undefined') {  
    //   let plist = '';
    //   if (params.indexOf('p-') != -1) {
    //     let param = params.match(/p-(\S*)/)[1];//参数
    //     plist = param.split('_');
    //   } else {
    //     let param = params.match(/p=(\S*)/)[1];//参数
    //     plist = param.split('#');
    //   }
    //   if (plist[1]) {     
    //     if(plist[2])
    //       that.data.diningSN = plist[2];        //餐桌SN序列号
    //     else
    //       app.globalData.diningSid = plist[1];  //餐桌唯一标示符
    //   } 
    // } else {
    //   if (options.sid) {
    //     app.globalData.diningSid = options.sid; //餐桌唯一标示符
    //   }
    // }

   
    that.loadParams(options);
    that.getDiningTable();
    that.log(JSON.stringify(options), 'wxapp_onload');
  },
  //加载参数
  loadParams: function(options){    
    let plist = '';
    if (options.q) {
      var url = decodeURIComponent(options.q);
      let params = utils.getQuery(url,'scene'); //扫普通二维码      
      if (params.indexOf('p-') != -1) {
        plist = params.match(/p-(\S*)/)[1].split('_');//参数
      } else {
        plist= params.match(/p=(\S*)/)[1].split('#') ;//参数
      }
      
      if(plist[2])
        this.data.diningSN = plist[2];        //餐桌SN序列号
      else if(plist[1])
        app.globalData.diningSid = plist[1];  //餐桌唯一标示符   
    }else if (options.sid) {
      app.globalData.diningSid = options.sid; //餐桌唯一标示符
    }
  },

  // 获取下单设置
  getStaffExtend: function (cardId) {
    let that = this;
    if (!cardId) {
      cardId = 0;
    }
    wx.request({
      url: app.globalData.host + '/api/staff/GetStaffExtend?staffid=' + cardId + '&keyword=30',
      success: function (res) {
        if (res.data.Code == 0) {
          if (res.data.Data.Value) {
            wx.setStorageSync('paytype', res.data.Data.Value);
            that.setData({
              payType: res.data.Data.Value
            })
          }
        }
      }
    })
  },

  decodeUnicode: function (str) {
    str = str.replace(/\\/g, "%");
    return unescape(str);
  },

  toPayOrder: function () {
    let that = this;
    let cartResult = this.data.cartResult;
    let selList = ''
    for (let i = 0; i < cartResult.length; i++) {
      if (cartResult[i].IsSelected) {
        selList += '0_' + cartResult[i].OrderProductInfo.Pid + ',';
      }
    }
    if (selList == '') {
      wx.showToast({title: '请选择菜品'})
      return;
    }
    if (selList) {
      wx.navigateTo({
        url: '../orderPayDine/index?sel=' + selList + '&sumprice=' + this.data.sumPrice + '&saleUid=' + that.data.saleUid,
      })
    }
    this.setData({
      selList: selList
    })
  },
  // 转为unicode 编码
  encodeUnicode: function (str) {
    var res = [];
    for (var i = 0; i < str.length; i++) {
      res[i] = ("00" + str.charCodeAt(i).toString(16)).slice(-4);
    }
    return "\\u" + res.join("\\u");
  },
  delProducts: function () {
    let that = this;
    let pids = '';
    let selList = "_";
    let cartResult = that.data.cartResult;
    for (let i = 0; i < cartResult.length; i++) {
      if (cartResult[i].IsSelected == 1) {
        pids += cartResult[i].OrderProductInfo.Pid + ',';
      }
    }
    pids = pids.substr(0, pids.length - 1);
    if (pids == '') {
      wx.showToast({
        title: '请选择商品',
        mask: true
      })
      return;
    }

    utils.confirm('是否删除？',function(){
      wx.request({
        url: app.globalData.host + '/api/Cart/DelProducts?pids=' + pids + '&uid=' + app.globalData.userInfo.Uid + '&selList=' + selList,
        success: function (res) {
          if (res.data.Code == 0) {
            wx.showToast({
              title: '删除成功'
            })
            that.getCartInfo();
          } else {
            wx.showModal({
              title: '提示',
              content: res.data.Message,
              showCancel: false
            })
          }
        }
      })
    });
  },

  // 获取购物车数据
  getCartInfo: function () {
    let that = this;
    wx.showLoading({title: '加载中'})
    wx.request({
      url: app.globalData.host + '/api/cart/SessionIndex',
      data: {
        sid: app.globalData.diningSid,
        createUid: that.data.createUid
      },
      method: 'POST',
      success: function (res) {
        wx.hideLoading();
        if (res.data.Code == 0) {
          let cartResult = [];    
          let optionIds = '';
          if (res.data.Data.StoreCartList.length > 0) {
            cartResult = res.data.Data.StoreCartList[0].CartProductList;
            for (let i = 0; i < cartResult.length; i++) {
              if (cartResult[i].OrderProductInfo.ShowImg.indexOf('ps') != -1) {
                cartResult[i].OrderProductInfo.ShowImg = utils.formatAvaterByProHead(cartResult[i].OrderProductInfo.ShowImg);
              } else {
                cartResult[i].OrderProductInfo.ShowImg = utils.formatAvater(cartResult[i].OrderProductInfo.ShowImg, 'https://static.711688.net.cn/upload/store/' + app.globalData.storeId + '/product/editor/');
              }
              cartResult[i].OrderProductInfo.OptionName = '';
              if (cartResult[i].OrderProductInfo.OptionIds) {
                optionIds += optionIds =='' ? '' : ',';
                optionIds += cartResult[i].OrderProductInfo.OptionIds;
              }
            }            
            that.setData({
              cartResult: cartResult,
              loadingMoreHiddens: false,
              sumPrice: res.data.Data.OrderAmount
            })
            that.getProductOptionList(optionIds);            
          } else {            
            wx.request({
              url: app.globalData.host + "/api/Cart/GetSessionCartPrintCount?sid=" + app.globalData.diningSid,
              success: function (res) {
                if (res.data.Code == 0) {
                  if (res.data.Data == 0) {//待付款判断
                    wx.reLaunch({
                      url: '/pages/classes-new/index'
                    })
                  } else {
                    wx.navigateTo({
                      url: '../orderPayDine/index?sumprice=' + that.data.sumPrice + '&saleUid=' + that.data.saleUid,
                    })
                  }
                }
              }
            })
          }
        } else {
          utils.showModal(res.data.Message);         
        }
      }
    })
  },
  //商品规格
  getProductOptionList: function (optionids) {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/product/GetProductOptionList?optionIds=' + optionids,
      success: function (res) {
        if (res.data.Code == 0) {
          let list=[]; 
          let cartResult = that.data.cartResult;
          //汇总所有规格
          for (let i = 0; i < res.data.Data.length; i++) {
            let optionList = res.data.Data[i].OptionList;
            for (let j = 0; j < optionList.length; j++) {
              list.push(optionList[j]);   
            }
          }
          //商品对应的规格
          for(let i = 0; i < cartResult.length; i++){
            let product = cartResult[i].OrderProductInfo;
            for (let j = 0; j < list.length; j++) {
              if(product.OptionIds.indexOf(list[j].OptionId)> -1){
                product.OptionName +=  product.OptionName == '' ? '': '/';
                product.OptionName += list[j].Name;
              }              
            }
          }
          that.setData({
            cartResult: cartResult
          });
        } else {         
          utils.showModal(res.data.Message);
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this;
    if (app.globalData.userInfo) {
      console.log("用户信息存在")
      setTimeout(function() {
        that.getCouponCheck();  //延时,防止cardId不存在
      }, 500);      
    } else {
      console.log("用户信息不存在,延时加载")
      setTimeout(function () {
        this.onShow();
      }.bind(that), 1000)
    }
  },
  // 减数量
  jianShopCar: function (e) {
    let that = this;
    var pid = e.currentTarget.dataset.pid;
    let count = e.currentTarget.dataset.count;
    let recordid = e.currentTarget.dataset.recordid;
    if (count < 2) {
      utils.confirm('是否删除？',function(){
        that.jianShopCarConfirm(pid, count, recordid);
      });      
    } else {
      that.jianShopCarConfirm(pid, count, recordid);
    }
  },
  jianShopCarConfirm: function (pid, count, recordId) {
    var that = this;
    let cartResult = that.data.cartResult;
    let sellist = '';
    for (let i = 0; i < cartResult.length; i++) {
      if (cartResult[i].OrderProductInfo.Pid == pid) {
        sellist = '0_' + pid;
        break;
      }
    }
    that.ChangeCount(pid,count - 1, recordId);
  },
  // 加购物车
  addShopCar: function (e) {
    var that = this;
    var pid = e.currentTarget.dataset.pid;
    let buynum = e.currentTarget.dataset.buynum;
    let recordId = e.currentTarget.dataset.recordid;
    let selList = '0_' + pid;
    wx.request({
      url: app.globalData.host + '/api/Store/Product?pid=' + pid,
      success: function (res) {
        if (res.data.Code == 0) {
          var p = res.data.Data;
          if (p.ProductInfo.State == 1) {
            utils.showModal('商品已下架');
            return;
          }
          if (p.StockNumber <= buynum) {
            utils.showModal('商品库存不足');
            return;
          }
          if (p.SinglePromotionInfo) {
            if (p.SinglePromotionInfo.DayBuyCount > 0) {//每天限购一份
              wx.showToast({
                title: '每天限购一份',
                duration: 1000
              })
              return;
            } else {
              wx.showToast({
                title: '限购一份',
                duration: 1000
              })
              return;
            }
          }
          that.ChangeCount(pid, buynum + 1, recordId);
        } else {
          utils.showModal(res.data.Message);         
        }
      },
    })
  },
  selectGoods: function (e) {
    let that = this;
    let pid = e.currentTarget.dataset.pid;
    let price = parseFloat(e.currentTarget.dataset.shopprice);
    let count = parseInt(e.currentTarget.dataset.count);
    let sumPrice = that.data.sumPrice;
    let cartResult = that.data.cartResult;
    for (let i = 0; i < cartResult.length; i++) {
      if (cartResult[i].OrderProductInfo.Pid == pid) {
        cartResult[i].IsSelected = !cartResult[i].IsSelected;
        if (cartResult[i].IsSelected) {
          sumPrice = parseFloat(sumPrice) + parseFloat(count * price);
        } else {
          sumPrice = parseFloat(sumPrice) - parseFloat(count * price);
        }
        that.setData({
          cartResult: cartResult,
          sumPrice: parseFloat(sumPrice).toFixed(2)
        })
      }
    }
  },
  //输入框
  blurNumber: function (e) {
    var that = this;
    if(isNaN(e.detail.value) || parseInt(e.detail.value) < 1){
      wx.showToast({title: '数量不能少于1', icon:'none'})
      return;
    } 
    // let cartResult = that.data.cartResult;
    var pid = e.currentTarget.dataset.pid;
    let recordId = e.currentTarget.dataset.recordid; 
    that.ChangeCount(pid, e.detail.value, recordId);
  },
  //更改数量
  ChangeCount: function(pid, buyCount, recordid){
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/cart/ChangeSessionProductCount',
      data: {
        pid: pid,
        buyCount: buyCount,
        sid: app.globalData.diningSid,
        uid: app.globalData.userInfo.Uid,
        selList:  '0_' + pid,
        recordId: recordid
      },
      success: function (res) {
        if (res.data.Code == 0) {
          that.getCartInfo();
        } else {       
          utils.showModal(res.data.Message);
        }
      }
    })
  },
  bindRemark: function (e) {
    let remark = e.detail.value;
    this.setData({
      remark: remark
    })
  },
  log: function(msg,type){
    wx.request({
      url: app.globalData.host + "/api/aliapp/log?msg=" + msg + '&type='+ type,
      success: function (res) {       
      },
    })
  }

})